package org.legzo.castorranker.web;

import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.PropertyListView;
import org.legzo.castorranker.RankerService;
import org.legzo.castorranker.ranker.Game;
import org.legzo.castorranker.ranker.Player;

public class HomePage extends WebPage {

	public HomePage() {

		RankerService rankerService = RankerApplication.get().getRankerService();
		List<Player> players = rankerService.getPlayers();

		Collections.sort(players, new Comparator<Player>() {
			public int compare(Player o1, Player o2) {
				return (int) (o2.getRanking() - o1.getRanking());
			}
		});

		PropertyListView<Player> playerList = buildPlayerList(players);
		add(playerList);
	}

	private PropertyListView<Player> buildPlayerList(final List<Player> players) {
		PropertyListView<Player> playersList = new PropertyListView<Player>("playersList", players) {
			private static final long serialVersionUID = 4289069821176726588L;

			@Override
			protected void populateItem(final ListItem<Player> item) {
				RankerService rankerService = RankerApplication.get().getRankerService();
				List<Game> games = rankerService.getGames();

				Date lastPlayedDate = games.get(games.size() - 1).getDate();

				Player currentPlayer = item.getModelObject();
				item.add(new Label("position", "" + (players.indexOf(currentPlayer) + 1)));
				item.add(new Label("name"));
				item.add(new Label("ranking"));

				item.add(new Label("lastRankingVariation", ""
						+ currentPlayer.getRankingVariationForDate(lastPlayedDate)));
			}
		};

		return playersList;
	}

}
